import datetime
from flask import Blueprint, request
from static.connect.conn_mysql import Connect


app_phone_code = Blueprint('app_phone_code', __name__)


@app_phone_code.route('/app_phone_code', methods=['POST'])
def phone_code():
    # 第一步：获取提交过来的手机和验证码
    phone = request.form.get('phone')
    verify_code = request.form.get('verify_code')

    if not all([phone, verify_code]):

        return {
            'status': -1,
            'errorCode': 41,
            'errorMsg': "提交的参数不能为空",
            'resultBody': None,
        }

    with Connect() as c:
        sql = 'SELECT * FROM vcode WHERE phone=%s AND verify_code=%s'

        result = c.select_one(sql, (phone, verify_code))

    if not result:

        return {
            'status': -1,
            'errorCode': 42,
            'errorMsg': "请重新确认验证码",
            'resultBody': None,
        }

    result_time = result['regedate']  # 获取验证码的时间
    now_time = datetime.datetime.now()  # 现在的时间
    expiry_date = datetime.timedelta(seconds=60)  # 这是一个时间量

    if not result_time + expiry_date > now_time:  # 如果失效

        return {
            'status': -1,
            'errorCode': 43,
            'errorMsg': "验证码已经失效",
            'resultBody': None,
        }

    return {
        'status': 1,
        'errorCode': None,
        'errorMsg': None,
        'resultBody': "验证通过",
    }
